package cn.stylefeng.guns.core.util;


import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 利用HttpClient进行post请求的工具类
 * @ClassName: HttpClientUtil
 * @Description: TODO
 * @author Devin <xxx>
 * @date 2017年2月7日 下午1:43:38
 *
 */
public class HttpClientUtil {

    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    @SuppressWarnings("resource")
    public static String doPost(String url,String jsonstr,String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();

            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }
    /**
     * 参数以UFT-8形式传递
     * @param url
     * @param paramsMap
     * @param charset 参数的编码格式
     * @return
     */
    @SuppressWarnings("resource")
    public static String doPost(String url,Map<String, String> paramsMap,String charset){
        HttpPost httpPost;
        String result = null;
        if(StringUtils.isBlank(url)){
            return "";
        }
        charset= ToolUtil.isAllEmpty(charset)?CHARSET:charset;
        try{
            httpPost = new HttpPost(url);
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            for(String key:paramsMap.keySet()){
                param.add(new BasicNameValuePair(key, paramsMap.get(key)));
            }
            if(param!=null && param.size()>0){
                httpPost.setEntity(new UrlEncodedFormEntity(param,charset));
            }
            httpPost.addHeader(new BasicHeader("Cookie","id=408; JSESSIONID=646BB7AA4B42FA5E44B244428E4015DB"));
            result=doExecute(httpPost, charset);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 执行HttpPost
     * @param httpPost
     * @param charset
     * @return
     */
    public static String doExecute(HttpPost httpPost, String charset){
        String result = null;
        try {
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != 200){
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
                EntityUtils.consume(resEntity);
//				response.close();
            }
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

}
